package com.tgy.leetcode;

/**
 * https://leetcode-cn.com/problems/single-number-ii/
 */
public class _137_只出现一次的数字_II {

    /**
     * 三进制进行异或
     * @param nums
     * @return
     */
    public static int singleNumber01(int[] nums) {

        if (nums.length == 1) {

            return nums[0];
        }

        /**
         * 3进制
         */
        int res = 0;
        int add;
        int step;
        for (int num : nums) {

            add = 0;
            step = 1;
            while (res != 0 || num != 0) {

                int bit = (res % 3 + num % 3) % 3;
                add = bit * step + add;
                res /= 3;
                num /= 3;
                step *= 3;
            }
            res = add;
        }

        return res;
    }

    public static int singleNumber(int[] nums) {


        int res = 0;
        int count;
        for (int i = 0; i <= 31; i++) {

            count = 0;
            for (int num : nums) {

                if (((num >> i) & 1) != 0) {

                    count++;
                }
            }

            if (count % 3 != 0) {

                res += (1 << i);
            }
        }

        return res;
    }

    public static void main(String[] args) {

        int n = 3;
//        int[] nums = {0,1,0,1,0,1,99};
        /**
         * 10
         * 11
         * 11
         * 10
         * 11
         * 10
         * 101
         */
//        int[] nums = {3,4,4,3,3,4,10};
//        3 % 3 = 0
        int[] nums = {-2,-2,-2,1,1,4,1,4,4,-4};

        System.out.println(singleNumber(nums));
    }
}
